package com.copd.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

import com.copd.entity.User;
import com.copd.mapper.UserMapper;

@Component
public class JwtUtil {
    private static final Logger logger = LoggerFactory.getLogger(JwtUtil.class);

    @Value("${jwt.secret}")
    private String secret;

    @Value("${jwt.expiration}")
    private Long expiration;
    
    @Autowired
    private UserMapper userMapper;

    public String generateToken(String username) {
        logger.debug("Generating token for username: {}", username);
        Map<String, Object> claims = new HashMap<>();
        String token = createToken(claims, username);
        logger.debug("Generated token: {}", token);
        return token;
    }

    private String createToken(Map<String, Object> claims, String subject) {
        logger.debug("Creating token for subject: {}", subject);
        String token = Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + expiration * 1000))
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
        logger.debug("Created token: {}", token);
        return token;
    }

    public Boolean validateToken(String token, String username) {
        try {
            logger.debug("Validating token for username: {}", username);
            final String tokenUsername = extractUsername(token);
            boolean isValid = tokenUsername.equals(username) && !isTokenExpired(token);
            logger.debug("Token validation result: {}", isValid);
            return isValid;
        } catch (Exception e) {
            logger.error("Error validating token: {}", e.getMessage(), e);
            return false;
        }
    }

    public String extractUsername(String token) {
        try {
            logger.debug("Extracting username from token");
            String username = extractClaim(token, Claims::getSubject);
            logger.debug("Extracted username: {}", username);
            return username;
        } catch (Exception e) {
            logger.error("Error extracting username from token: {}", e.getMessage(), e);
            throw e;
        }
    }

    public Date extractExpiration(String token) {
        try {
            logger.debug("Extracting expiration from token");
            Date expiration = extractClaim(token, Claims::getExpiration);
            logger.debug("Extracted expiration: {}", expiration);
            return expiration;
        } catch (Exception e) {
            logger.error("Error extracting expiration from token: {}", e.getMessage(), e);
            throw e;
        }
    }

    public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
        try {
            logger.debug("Extracting claim from token");
            final Claims claims = extractAllClaims(token);
            T result = claimsResolver.apply(claims);
            logger.debug("Extracted claim: {}", result);
            return result;
        } catch (Exception e) {
            logger.error("Error extracting claim from token: {}", e.getMessage(), e);
            throw e;
        }
    }

    private Claims extractAllClaims(String token) {
        try {
            logger.debug("Extracting all claims from token");
            Claims claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
            logger.debug("Extracted claims: {}", claims);
            return claims;
        } catch (Exception e) {
            logger.error("Error extracting claims from token: {}", e.getMessage(), e);
            throw e;
        }
    }

    public Integer getUserIdFromToken(String token) {
        try {
            logger.debug("Extracting userId from token");
            String username = extractUsername(token);
            
            // 根据用户名查找用户
            User user = userMapper.findByUsername(username);
            if (user == null) {
                logger.error("User not found for username: {}", username);
                return null;
            }
            
            Integer userId = user.getUserId();
            logger.debug("Extracted userId: {}", userId);
            return userId;
        } catch (Exception e) {
            logger.error("Error extracting userId from token: {}", e.getMessage(), e);
            return null;
        }
    }

    private Boolean isTokenExpired(String token) {
        try {
            logger.debug("Checking if token is expired");
            Date expiration = extractExpiration(token);
            boolean isExpired = expiration.before(new Date());
            logger.debug("Token expiration check result: {}", isExpired);
            return isExpired;
        } catch (Exception e) {
            logger.error("Error checking token expiration: {}", e.getMessage(), e);
            throw e;
        }
    }
} 